<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>欢迎页面-X-admin2.0</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" th:href="@{/css/font.css}">
    <link rel="stylesheet" th:href="@{/css/xadmin.css}">
    <script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}"></script>
    <script th:src="@{/js/ions_alert.js}"></script>
    <script th:src="@{/common/common.js}"></script>
    <script th:src="@{/js/sweetalert.min.js}"></script>
    <link rel="stylesheet" th:href="@{/css/sweetalert.css}">
</head>

<body>
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a href="">演示</a>
        <a>
          <cite>导航元素</cite></a>
      </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon" style="line-height:30px">ဂ</i></a>
</div>
<div class="x-body">
    <div class="layui-row">
        <div class="layui-form layui-col-md12 x-so">
            <input value="" type="text" name="no" placeholder="请输入商品码" autocomplete="off"
                   class="layui-input" id="no">
            <button class="layui-btn" lay-submit="" lay-filter="search" id="search"><i class="layui-icon">&#xe615;</i></button>
        </div>

    </div>
    <xblock>
        <span class="x-right" style="line-height:40px">您购买了：<span id="many">0</span> 件商品</span>
    </xblock>
    <table class="layui-table">
        <thead>
        <tr>
            <th>商品编码</th>
            <th>商品名称</th>
            <th>单价</th>
            <th>共积分</th>
            <th>积分</th>
            <th>商品数量</th>
            <th>价格</th>
            <th>操作<input type="hidden" th:value="${FORSALE}" id="forSale"></th>

        </tr>
        </thead>
        <tbody id="waresList">
        </tbody>
    </table>
    <div>
        <span class="x-right" style="line-height:40px">共积了： <span id="point">0</span>分</span>&nbsp;&nbsp;&nbsp;
        <span class="x-right" style="line-height:40px">您共消费了： ￥<span id="price">0</span>元</span>
    </div>
    <div class="page">
        <div>
            <button class="layui-btn" id="balance">
                结算
            </button>
        </div>
    </div>
    <div class="layui-input-inline">
        <input type="text" name="username" required lay-verify="required" placeholder="输入手机号" autocomplete="off" class="layui-input" id="phone">

    </div>
    <span id="username"></span>
</div>
</body>
<script>

    //定义一个数组，存放添加的商品信息
    var nos = [];
    //定义一个  商品总价
    let allPrice = 0;
    //定义总积分
    let allPoints = 0;
    function cancel(no){
        $("#"+no).click(function () {

            var myNos = nos;
            for (var i = 0;i < myNos.length;i++){
                var xNo = myNos[i];
                // console.log(xNo);
                // console.log(no);
                if(xNo+'' === no+''){
                    let index = myNos.indexOf(xNo);
                    if(index > -1){
                        myNos.splice($.inArray(xNo+'',myNos),1);
                        // myNos.slice(index,1);
                        allPrice = 0;
                        allPoints = 0;
                        //所有在 数组里面的 商品都拿出来计算
                        for (let x = 0; x < nos.length;x++) {
                            allPrice += Number($("#"+nos[x]+" .price").text());
                            allPoints += Number($("#"+nos[x]+" .point").text());
                        }
                        $(this).remove();
                        $("#many").text(nos.length);
                    }
                    break;
                }
            }
        })
    }
    //计算价格和积分
    function calc(param,no,price,point){
        let number = $("#"+no+" .number").text();

        //设置总价
        if(param === 'add'){
            number ++;
            //计算自己的价格， 数量*单价
            let itPrice = number*price;
            let itPoint = number*point;
            //设置自己的价格和数量
            $("#"+no+" .price").text(itPrice.toFixed(2));
            $("#"+no+" .point").text(itPoint.toFixed(2));
            $("#"+no+" .number").text(number);
            //计算总价
            allPrice = 0;
            allPoints = 0;
            //所有在 数组里面的 商品都拿出来计算
            for (let x = 0; x < nos.length;x++) {
                allPrice += Number($("#"+nos[x]+" .price").text());
                allPoints += Number($("#"+nos[x]+" .point").text());
            }
            //设置总价
            $("#price").text((allPrice).toFixed(2));
            $("#point").text(allPoints.toFixed(2));
            $("#many").text(nos.length);


        }else if(param === 'sub'){
            if(number === '1'){
            }else {
                number --;
                //重新设置数量和价格
                $("#"+no+" .number").text(number);
                $("#"+no+" .price").text(((number)*price).toFixed(2));
                $("#"+no+" .point").text(((number)*point).toFixed(2));
                //所有在 数组里面的 商品都拿出来计算
                allPrice = 0;
                allPoints = 0;
                for (let x = 0; x < nos.length;x++) {
                    allPrice += Number($("#"+nos[x]+" .price").text());
                    allPoints += Number($("#"+nos[x]+" .point").text());
                }
                $("#price").text((allPrice).toFixed(2));
                $("#point").text(allPoints.toFixed(2));
                $("#many").text(nos.length.toFixed(2));
            }
        }else {

        }
    }

    $(function () {

        //要是想要积分的用户可以填写手机号
        $("#phone").keyup(function (event) {
            let phone = $(this).val();
            if(phone.length === 11 && event.keyCode !== 17){
                //查询
                $.ajax({
                    url:"/sales/phoneFindUser",
                    type:"PUT",
                    data: {
                        phone:phone
                    },
                    success:function (resultInfo) {

                        $("#phone").text("");

                        if(resultInfo.flag){
                            //如果存在，就把名字拿出来看看
                            $("#username").text(resultInfo.data.username);
                        }else {
                            //这个用户不存在
                            $("#username").text("这个用户不存在");
                        }
                    },
                    error:function () {

                    }
                })

            }else if(phone.length === 0){
                //若删除了手机号，删除用户 也就是设置为空
                $("#username").text("");
            }
        });

        //按下会有这样的事件
        $("#no").keyup(function (event) {
            let no = $(this).val();
            //只要是13位，就自动查 但是要排除 粘贴时候的控制按键，会触发两次keyup
            if(no.length === 13 && event.keyCode !== 17){
                // console.log(number);
                var t = 0;
                // console.log(nos);
                //先判断是否已经存在
                for (var i = 0;i < nos.length;i++){
                    var xNo = nos[i];
                    // console.log("每个在里面的值是："+xNo);
                    if(xNo === no){
                        t = 1;
                        break;
                    }
                }
                //说明已经存在
                if(t === 1){
                    // var temp = $("#"+no+" .number").text();
                    //调用加法算法，注意传入的必须是 单价
                    calc('add',no,$("#"+no+" .simPrice").text(),$("#"+no+" .simPoint").text());
                    //数量增加
                    // $("#"+no+" .number").text(++temp);
                    $("#no").val("");
                }else {
                    //尚未存在，添加进去
                    nos.push(no);
                    //查询
                    toWares(no);
                }
                // console.log(nos);
                // $(this).text("");
            }
        });
        //单击查询时候也会查
        $("#search").click(function () {
            let no = $("#no").val();
            //但是为空不能查
            if( no.trim().length > 0 ){
                toWares(no);
            }
        });


        //结算的时候
        $("#balance").click(function () {
            let allPrice = $("#price").text();
            let forSale = $("#forSale").val();
            let result = window.confirm("您一共消费了"+(allPrice)+" 元，优惠后价格"+((forSale*allPrice).toFixed(2))+" 元，确认购买吗？");
            if(result){
                var wares = [];
                for (let i = 0; i < nos.length; i++) {
                    var number = $("#"+nos[i]+" .number").text();
                    var simPrice = $("#"+nos[i]+" .simPrice").text();
                    var simPoint = $("#"+nos[i]+" .simPoint").text();
                    var ware = {
                        number:number,
                        no:nos[i],
                        price:simPrice,
                        point:simPoint,
                        username:$("#username").text()
                    };
                    wares.push(ware);
                }
                $.ajax({
                    url: "/sales/sellWares",
                    data: {
                        waresList: JSON.stringify(wares),
                        allPrice:allPrice,
                        allPoint:$("#point").text(),
                        username:$("#username").text()
                    },
                    dataType:"JSON",
                    type:"PUT",
                    success:function (resultInfo) {
                        if(resultInfo.flag){
                            alert(resultInfo.message);
                            window.location.reload();
                        }else {
                            console.log((resultInfo.message));
                        }
                    },
                    error:function () {

                    }
                })
            }

        });
    });

    function toWares(no) {
        $.ajax({
            url: "/sales/findWares",
            type:"PUT",
            data:{
                number: no
            },
            success:function (resultInfo) {
                let allPrice = $("#price").text();
                let allPoints = $("#point").text();

                if(resultInfo.flag){
                    // console.log("成功了");
                    //获取当前的内容
                    let text = $("#waresList").html();
                    //加上参与的
                    text += '<tr id="'+resultInfo.data.no+'">\n' +
                        '            <td>'+resultInfo.data.no+'</td>\n' +
                        '            <td>'+resultInfo.data.name+'</td>\n' +
                        '            <td class="simPrice">'+resultInfo.data.retailPrice+'</td>\n' +
                        '<td class="point"> '+resultInfo.data.points+' </td>'+
                        '            <td class="simPoint">' +
                        +resultInfo.data.points+
                        '            </td>' +
                        '<td>\n' +
                        '                <i class="layui-icon " style="font-size: 36px; color: red;" onclick="calc(\'sub\','+resultInfo.data.no+','+resultInfo.data.retailPrice+','+resultInfo.data.points+')">-</i>\n' +
                        '                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n' +
                        '                <span class="number" style="font-size: 18px;">1</span>\n' +
                        '                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n' +
                        '                <i class="layui-icon" style="font-size: 30px; color: green;" onclick="calc(\'add\','+resultInfo.data.no+','+resultInfo.data.retailPrice+','+resultInfo.data.points+')" >+</i>\n' +
                        '        </td>'+
                         '<td class="price">'+(resultInfo.data.retailPrice)+'</td>'+
                        '          <td><a onclick="cancel('+resultInfo.data.no+')" style="cursor: pointer" class="layui-btn layui-btn-mini layui-btn-danger delete_btn">\n' +
                        '                   <i class="layui-icon">&#x1006;</i>取消\n' +
                        '                </a>\n' +
                        '          </td>\n' +
                        '        </tr>';
                    $("#waresList").html(text);
                    allPrice = 0;
                    allPoints = 0;
                    for (let i = 0; i < nos.length; i++) {
                        allPrice += Number($("#"+nos[i]+" .price").text());
                        allPoints += Number($("#"+nos[i]+" .point").text());
                    }

                    // console.log("计算完是："+allPrice);
                    $("#price").text((allPrice));
                    $("#point").text(allPoints);
                    $("#many").text(nos.length);
                    $("#no").val("");
                }else {
                    alert(resultInfo.message);
                }
            },
            error:function (e) {
                console.log("不仅没成功，还失败了");
            }
        })
    }
</script>

</html>